package com.ukao.steward.ui.valetRunners.gathering;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ukao.steward.R;
import com.ukao.steward.base.MvpFragment;
import com.ukao.steward.bean.BalanceBean;
import com.ukao.steward.bean.OrderInfoBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.eventbus.PayEvent;
import com.ukao.steward.pesenter.valetRunners.QuiltSweepPesenter;
import com.ukao.steward.util.ActivityUtils;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.DensityUtils;
import com.ukao.steward.util.KeyBoardUtil;
import com.ukao.steward.util.T;
import com.ukao.steward.view.valetRunners.QuiltSweepView;
import com.ukao.steward.widget.StateImageView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;

import static com.ukao.steward.R.id.code;
import static com.ukao.steward.R.id.main_layout;
import static com.ukao.steward.eventbus.PayEvent.Message.PAY_SUCCEED;


public class AlipayWeChatFragment extends MvpFragment<QuiltSweepPesenter> implements QuiltSweepView {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(code)
    ImageView codeImage;
    Unbinder unbinder;
    @BindView(R.id.switch_tv)
    TextView switchTv;
    @BindView(R.id.remark)
    EditText remark;
    @BindView(R.id.sweep_btn)
    StateImageView sweepBtn;
    @BindView(main_layout)
    LinearLayout mainLayout;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private boolean isOpen;
    private OrderInfoBean mOrderInfoBean;
    private Handler mHandler = new Handler();
    private boolean loadfinish = false;
    private BalanceBean mBalance;
    private boolean isAlipayEnter;


    /**
     * @param mOrderInfoBean 订单信息
     * @param isAlipayEnter  是否是支付宝哦进入
     */
    public static AlipayWeChatFragment newInstance(OrderInfoBean mOrderInfoBean, boolean isAlipayEnter) {
        AlipayWeChatFragment fragment = new AlipayWeChatFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARG_PARAM1, mOrderInfoBean);
        args.putBoolean(ARG_PARAM2, isAlipayEnter);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mOrderInfoBean = getArguments().getParcelable(ARG_PARAM1);
            isAlipayEnter = getArguments().getBoolean(ARG_PARAM2, false);
        }
    }

    @Override
    protected QuiltSweepPesenter createPresenter() {
        return new QuiltSweepPesenter(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_alipay_we_chat, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
    }

    @Override
    protected void initListener() {
        super.initListener();
        remark.setFocusable(true);
        remark.setFocusableInTouchMode(true);
        remark.requestFocus();
        remark.setOnEditorActionListener(mOnEditorActionListener);
    }


    private TextView.OnEditorActionListener mOnEditorActionListener = (v, actionId, event) -> {

        if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                || actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT) {

            if (remark.getVisibility()==View.VISIBLE){
                masterScanner(getText(remark));
                KeyBoardUtil.hideInputmethod(remark);
                remark.setText("");

                return  true;
            }


        }

        return false;
    };
    @Override
    protected void initView() {


    }


    @Override
    public void loadQRCodeData(BalanceBean mBalance) {
        loadfinish = true;
        this.mBalance = mBalance;
        if (mOrderInfoBean!=null) mOrderInfoBean.setIsbundle(true);
        createQRCode(mBalance.getCodeUrl());

    }

    private void createQRCode(String code) {
        codeImage.setImageBitmap(QRCodeEncoder.syncEncodeQRCode(code, DensityUtils.dip2px(170)));
        postDelayedquery();
    }

    /**
     * 交易状态
     *
     * @param mBalance
     */
    @Override
    public void queryStatusData(BalanceBean mBalance) {
        switch (mBalance.getStatus()) {
            case -1:

                removeCallbacks();
                T.show("交易失败");
                break;
            case 0: /*status -1.交易失败 0.交易中 1.交易成功*/

                removeCallbacks();
                postDelayedquery();
                break;
            case 1:

                removeCallbacks();
                loadPayData("");


                break;


        }
    }

    /**
     * 解绑成功
     */
    @Override
    public void unlockOrderData(boolean isMainStyle) {
        if (isMainStyle){
            if (mOrderInfoBean!=null) mOrderInfoBean.setIsbundle(false);
            return;
        }
        int balance = mOrderInfoBean.getUseBalance();
        if (isAlipayEnter) {
            mvpPresenter.wxUnifiedOrder(mOrderInfoBean.getOrderId(), balance, false, mOrderInfoBean.isUseUPay(), mOrderInfoBean.getCpnRelId());
        } else {
            mvpPresenter.wxUnifiedOrder(mOrderInfoBean.getOrderId(), balance, true, mOrderInfoBean.isUseUPay(), mOrderInfoBean.getCpnRelId());
        }
    }

    @Override
    public void unlockOrderFail() {

    }

    @Override
    public void loadPayData(String msg) {
            dismissProgressDialog();
           mOrderInfoBean.setPayFinish(true);
            PayEvent.postNoData(PAY_SUCCEED);



    }


    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        isVisible = true;
        createCode(mainLayout.getVisibility()==View.VISIBLE);
        postDelayedquery();

    }

    private void createCode(boolean  isMainStyle ) {

        if (isAlipayEnter) {
            if (!mOrderInfoBean.isIsEnableAli()) return;
            mvpPresenter.unlockOrder(mOrderInfoBean.getOrderId(),isMainStyle);
        } else {

            if (!mOrderInfoBean.isIsEnableWx()) return;
            mvpPresenter.unlockOrder(mOrderInfoBean.getOrderId(),isMainStyle);
        }
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        isVisible = false;
        loadfinish = false;
        codeImage.setImageBitmap(null);
        removeCallbacks();
    }

    public void postDelayedquery() {
        if (loadfinish && isVisible&&mainLayout.getVisibility()==View.GONE)
            mHandler.postDelayed(mRunnable, 1500);
    }

    Runnable mRunnable = new Runnable() {
        @Override
        public void run() {

            mvpPresenter.queryStatusBySeq(mBalance.getSeq());

        }
    };

    public void removeCallbacks() {
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        removeCallbacks();
        unbinder.unbind();
    }

    @OnClick({R.id.switch_tv,R.id.sweep_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.switch_tv:
                if ( mainLayout.getVisibility()==View.VISIBLE){  //被扫
                    mainLayout.setVisibility(View.GONE);
                    switchTv.setText( R.string.main_mode);
                    createCode(mainLayout.getVisibility()==View.VISIBLE);

                }else {  //主扫
                    codeImage.setImageBitmap(null);
                    mainLayout.setVisibility(View.VISIBLE);
                    mvpPresenter.unlockOrder(mOrderInfoBean.getOrderId(),mainLayout.getVisibility()==View.VISIBLE);
                    switchTv.setText(R.string.swept_mode);
                    remark.requestFocus();


                }

                break;
            case  R.id.sweep_btn:

                Intent mIntent = ActivityUtils.JumpToBundleActivity(_mActivity);
                startActivityForResult(mIntent , Constant.REQUEST_CODE);
                break;

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {

            switch (requestCode) {
                case Constant.REQUEST_CODE:
                    String  strCode=data.getStringExtra(Constant.ARG_PARAM1);
                    masterScanner(strCode);




                    break;
            }
        }

    }



    void masterScanner( String  strCode) {
        if (!CheckUtils.isEmpty(strCode)){
            int balance = mOrderInfoBean.getUseBalance();
            mvpPresenter.wxMainMicroPay(mOrderInfoBean.getOrderId(), balance+"",strCode ,!isAlipayEnter, mOrderInfoBean.isUseUPay(), mOrderInfoBean.getCpnRelId());
        }

    }



}
